package com.manor.main.login;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.manor.common.CommonAppConfig;
import com.manor.common.Constants;
import com.manor.common.activity.AbsActivity;
import com.manor.common.activity.BaseLocationActivity;
import com.manor.common.bean.UserBean;
import com.manor.common.constant.SharedPreferenceKey;
import com.manor.common.dialog.XVerifyPopup;
import com.manor.common.event.LoginSuccessEvent;
import com.manor.common.http.JHttpCallback;
import com.manor.common.interfaces.CommonCallback;
import com.manor.common.utils.GsonUtil;
import com.manor.common.utils.SharedPreferencesUtils;
import com.manor.common.utils.SpUtil;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.main.R;
import com.manor.main.activity.LoginGenderAgeActivity;
import com.manor.main.activity.MainActivity;
import com.manor.main.bean.LoginBean;
import com.manor.main.http.JMainHttpUtil;
import com.manor.main.http.MainHttpUtil;
import com.manor.main.utils.CodeTimeCount;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import kotlin.Unit;
import kotlin.jvm.functions.Function2;

/**
 * 手机验证码登录
 */
public class SmsLoginFragment extends Fragment {


    public static final String REGEX_PHONE = "^[0-9]{11}$";
    private Context mContext;
    private CodeTimeCount codeTimeCount;
    private boolean mFirstLogin;//是否是第一次登录.
    private String riskToken;

    public SmsLoginFragment() {

    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    public static SmsLoginFragment newInstance() {
        return new SmsLoginFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_v_code_login, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        TextView tvAgreement = view.findViewById(R.id.tv_agreement);
        if (mContext instanceof LoginActivity) {
            ((LoginActivity) mContext).dealAgreement(tvAgreement);
        }


        EditText etPhoneNumber = view.findViewById(R.id.et_phone_number);
        EditText etVCode = view.findViewById(R.id.et_code);
        TextView tvVcode = view.findViewById(R.id.tv_vcode);
        codeTimeCount = new CodeTimeCount(59000, 1000, tvVcode);

        tvVcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneNum = etPhoneNumber.getText().toString().trim();
                if (verifyPhone(phoneNum)) {
                    return;
                }
                doSmsMsg(phoneNum);
            }
        });

        view.findViewById(R.id.btn_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneNum = etPhoneNumber.getText().toString().trim();
                if (verifyPhone(phoneNum)) {
                    return;
                }

                String vCode = etVCode.getText().toString().trim();

                if (TextUtils.isEmpty(vCode)) {
                    ToastUtil.show("请输入验证码");
                    return;
                }
                login(phoneNum, vCode);
            }
        });

//        Toolbar toolbar = view.findViewById(R.id.toolbar);
//        if (mContext instanceof AbsActivity) {
//            ((AbsActivity) mContext).setSupportActionBar(toolbar);
//            ((AbsActivity) mContext).getSupportActionBar().setDisplayShowTitleEnabled(false);
//            ((AbsActivity) mContext).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (KeyboardUtils.isSoftInputVisible((AbsActivity) mContext)) {
//                        KeyboardUtils.hideSoftInput((AbsActivity) mContext);
//                    }
//                    ((AbsActivity) mContext).onBackPressed();
//                }
//            });
//        }
//        TextView tvTitle = view.findViewById(R.id.tv_title);
//        tvTitle.setText("短信登录");

        view.findViewById(R.id.tv_register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                // 隐藏键盘
                if (KeyboardUtils.isSoftInputVisible((AbsActivity) mContext)) {
                    KeyboardUtils.hideSoftInput((AbsActivity) mContext);
                }
                if (mContext instanceof LoginActivity) {
                    FragmentManager fragmentManager = ((LoginActivity) mContext).getSupportFragmentManager();
                    VCodeVerifyFragment vCodeFragment = (VCodeVerifyFragment) fragmentManager
                            .findFragmentByTag(VCodeVerifyFragment.class.getSimpleName());
                    if (vCodeFragment == null) {
                        vCodeFragment = VCodeVerifyFragment.newInstance();
                    }
                    Bundle args = new Bundle();
                    // 跳转到注册
                    args.putInt(VCodeVerifyFragment.FLAG_FROM_TYPE, 1);
                    args.putString(VCodeVerifyFragment.FLAG_TITLE_TEXT, "账号注册");
                    args.putString(VCodeVerifyFragment.FLAG_BTN_TEXT, "注册");

                    vCodeFragment.setArguments(args);

                    FragmentTransaction ft = fragmentManager.beginTransaction();
                    if (!vCodeFragment.isAdded()) {
                        ft.add(R.id.fl_container, vCodeFragment, VCodeVerifyFragment.class.getSimpleName());
                        ft.addToBackStack(VCodeVerifyFragment.class.getSimpleName());
                    } else {
                        ft.show(vCodeFragment);
                    }
                    ft.commit();
                }


            }
        });
    }

    /**
     * 登录
     */
    private void login(String phone, String smscode) {
        if (mContext instanceof BaseLocationActivity) {


            BaseLocationActivity activity = (BaseLocationActivity) mContext;
            if (BaseLocationActivity.npcCode == 0) {
                activity.showWaitingDialog(false);
                if (sun >= 3) {
                    // ToastUtil.show("无法获取您的位置，请走到开阔地带重试");
                    activity.dismissWaitingDialog();
                    sun = 0;
                } else {
                    Message msg = Message.obtain();
                    Bundle bundle = new Bundle();
                    bundle.putString("phone", phone);
                    bundle.putString("sms", smscode);
                    msg.setData(bundle);
                    msg.what = 0;
                    handler.sendMessageDelayed(msg, 1000);//发送消息
                    sun++;
                    return;
                }
            } else {
                activity.dismissWaitingDialog();
            }

            activity.showWaitingDialog(false);
            JMainHttpUtil.loginByMsg(phone, smscode, BaseLocationActivity.npcCode, new JHttpCallback() {
                @Override
                public void onSuccess(int code, String msg, String info) {
                    activity.dismissWaitingDialog();
                    if (code == 200) {
                        onMsgSuccess(code, msg, info);
                        SpUtil.getInstance().setStringValue(SpUtil.SP_MOBILE, phone);
                        SharedPreferencesUtils.putData(SharedPreferenceKey.PHONE, phone);
                    } else {
                        ToastUtil.show(msg);
                    }
                }

                @Override
                public void onError() {
                    super.onError();
                    activity.dismissWaitingDialog();
                }
            });
        }
    }

    private void onMsgSuccess(int code, String msg, String info) {
        if (code == 200 && !info.equals("")) {
            LoginBean loginBean = GsonUtil.gsonToBean(info, LoginBean.class);
            SharedPreferencesUtils.putData(SharedPreferenceKey.USER_NAME, loginBean.getNikeName());
            SharedPreferencesUtils.putData(SharedPreferenceKey.USER_ID, loginBean.getUid());

            BaseLocationActivity.parentSdNo = loginBean.getParentSdNo();
            SpUtil.getInstance().setStringValue(SpUtil.TX_IM_USER_SIGN, loginBean.getUsersig());
            MobclickAgent.onProfileSignIn(Constants.MOB_PHONE, loginBean.getUid());
            EventBus.getDefault().post(new LoginSuccessEvent());
            CommonAppConfig.getInstance().setLoginInfo(loginBean.getUid(), loginBean.getAccessToken(), true);
            SpUtil.getInstance().setStringValue(SpUtil.JAVA_TOKEN, loginBean.getTokenType() + " " + loginBean.getAccessToken());
            isFirstLogin(loginBean.getNikeName());
        } else {
            ToastUtil.show(msg);
        }
    }

    private void isFirstLogin(String name) {
        if ("".equals(name)) {
            //进入填写资料页面
            LoginGenderAgeActivity.forward(4);
        } else {
            //进入首页
            getBaseUserInfo();
        }
    }

    /**
     * 获取用户信息
     */
    private void getBaseUserInfo() {
        MainHttpUtil.getBaseInfo(new CommonCallback<UserBean>() {
            @Override
            public void callback(UserBean bean) {
                MainActivity.Companion.forward(mContext, mFirstLogin);
                if (mContext instanceof AbsActivity) {
                    ((AbsActivity) mContext).finish();
                }
            }
        });
    }


    private boolean verifyPhone(String phoneNum) {
        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtil.show("手机号码不能为空");
            return true;
        }
        if (!RegexUtils.isMatch(REGEX_PHONE, phoneNum)) {
            ToastUtil.show("手机号码格式不正确");
            return true;
        }
        return false;
    }

    private void doSmsMsg(String phone) {
        JMainHttpUtil.getIsWY(new JHttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                if (code == 200) {
                    if ("true".equals(info) && StringUtil.isEmpty(riskToken)) {
                        XVerifyPopup.Companion.load(getActivity(), new SimpleCallback(), new Function2<Boolean,
                                String, Unit>() {
                            @Override
                            public Unit invoke(Boolean boo, String s) {
                                if (boo) {
                                    riskToken = s;
                                    sendMsgCode(phone);
                                }
                                return null;
                            }
                        });
                    } else {
                        sendMsgCode(phone);
                    }
                }
            }
        });
    }


    private void sendMsgCode(String phone) {

        if (mContext instanceof AbsActivity) {
            ((AbsActivity) mContext).showWaitingDialog(false);
        }

        JMainHttpUtil.getSmsCode(phone, 2, riskToken, new JHttpCallback() {
            @Override
            public void onError() {
                super.onError();
                ToastUtil.show("服务器返回错误");
                if (mContext instanceof AbsActivity) {
                    ((AbsActivity) mContext).dismissWaitingDialog();
                }
            }

            @Override
            public void onSuccess(int code, String msg, String info) {
                if (mContext instanceof AbsActivity) {
                    ((AbsActivity) mContext).dismissWaitingDialog();
                }
                if (code == 200) {
                    codeTimeCount.start();
                    ToastUtil.show("验证码已通过短信发送至+86 " + phone);
                } else if (code == 1509) {
                    //验证失败，重新验证
                    riskToken = "";
                    ToastUtil.show(msg);
                } else {
                    ToastUtil.show(msg);
                }
            }
        });
    }

    private MyHandler handler = new MyHandler(this);

    public static class MyHandler extends Handler {

        private final WeakReference<SmsLoginFragment> reference;

        public MyHandler(SmsLoginFragment fragment) {
            reference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            SmsLoginFragment vCodeLoginFragment = reference.get();
            if (vCodeLoginFragment != null) {
                Bundle data = msg.getData();
                String phone = data.getString("phone");
                String sms = data.getString("sms");
                vCodeLoginFragment.login(phone, sms);
            }
        }
    }

    int sun = 0;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (codeTimeCount != null) {
            codeTimeCount.cancel();
            codeTimeCount = null;
        }
        handler.removeCallbacksAndMessages(null);
        handler = null;
    }
}